package cn.wolfcode.crm.util;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 异常处理:spring中的所有异常处理交给这个处理
 */
@ControllerAdvice
public class ExceptionsHandlerUtil {
    //带参数表示只处理指定类型
    @ExceptionHandler(UnauthorizedException.class)
    public void handleException(HttpServletResponse response,
                                HandlerMethod method) throws IOException {
        //如何区分是ajax还是普通请求
        //判断是普通请求,还是ajax请求(返回json数据)
        ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
        if (responseBody != null) {
            response.setContentType("application/json;charset=utf-8");
            JsonResult jsonResult = new JsonResult();
            jsonResult.markErrorMsg("没有操作请求");
            response.getWriter().print(new ObjectMapper().writeValueAsString(jsonResult));
        } else {
            response.sendRedirect("/noPermission.jsp");
        }
    }

}
